<template>
    <div>
        <el-dialog title="折扣管理" class="discountModel noselect"  :close-on-click-modal="false" :visible.sync="showDialog" :before-close="handleClose">
            <div style="margin: 20px;"></div>
            <el-form :model="modelForm" ref="modelForm" label-width="100px" class="demo-ruleForm" style="height: 600px; overflow-y: auto;overflow-x: hidden">
                <el-form-item label=" " prop="type" :rules="[ { required: true, message: '请选择折扣类型', trigger: 'blur'}]">
                  <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium">
                    <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                      <span>折扣类型</span>
                    </div>
                    <el-radio-group class="radio-group w-100p text-left" v-model="modelForm.type" :disabled="!isSave" >
                      <el-radio v-for="item in packageType" :label="item.key" :value="item.key" :key="item.key">
                        {{item.text}}</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item>
              <el-form-item label=" " prop="hasVip" :rules="[]" class="text-left" >
                <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium">
                  <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                    <span>适用场景</span>
                  </div>
                  <el-radio-group class="radio-group w-100p text-left" v-model="modelForm.useScene">
                    <el-radio v-for="item in useScenes" class="radio" :label="item.key" :value="item.text">{{item.text}}</el-radio>
                    <!--<el-radio class="radio"  :label="false">否</el-radio>-->
                  </el-radio-group>
                </div>
              </el-form-item>
<!--
              <el-form-item label=" " prop="hasVip" :rules="[]" class="text-left" >
                <div class="el-input el-input-group el-input-group&#45;&#45;prepend addprepend el-input&#45;&#45;medium">
                  <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                    <span>会员折</span>
                  </div>
                  <el-radio-group class="radio-group w-100p text-left" v-model="modelForm.hasVip">
                    <el-radio class="radio"  :label="true">是</el-radio>
                    <el-radio class="radio"  :label="false">否</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
-->
                <el-form-item label=" " prop="name" :rules="[{ required: true, message: '请输入折扣名称', trigger: 'blur'}]">
                    <el-input placeholder="请输入折扣名称" class="w-100p" v-model="modelForm.name" :maxlength="11" size="medium">
                        <template slot="prepend">
                            <el-tooltip placement="top" content="请填写折扣名称">
                                <el-button tabIndex="-1">折扣名称</el-button>
                            </el-tooltip>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label=" " v-if="modelForm.type=='AllSINGLE'" prop="discount" :rules="[{ required: true, message: '请输入折扣率', trigger: 'blur'},rules.numPot2]">
                    <el-input placeholder="请输入折扣率" @blur="isNumber(modelForm,'discount')" class="w-100p" v-model="modelForm.discount" size="medium">
                        <template slot="prepend">
                            <el-tooltip placement="top" content="（请填写折扣率，如10即10%，此项为必填项！）">
                                <el-button tabIndex="-1">正常折扣率</el-button>
                            </el-tooltip>
                        </template>
                        <template slot="append">%</template>
                    </el-input>
                </el-form-item>
                <el-form-item label=" " v-if="modelForm.type=='AllSINGLE'" prop="specialDiscount" :rules="[{ required: true, message: '请输入折扣率', trigger: 'blur'},rules.numPot2]">
                    <el-input placeholder="请输入特价折扣" @blur="isNumber(modelForm,'specialDiscount')" class="w-100p" v-model="modelForm.specialDiscount" size="medium">
                        <template slot="prepend">
                            <el-tooltip placement="top" content="（请填写折扣率，如10即10%，此项为必填项！）">
                                <el-button tabIndex="-1">特价折扣率</el-button>
                            </el-tooltip>
                        </template>
                        <template slot="append">%</template>
                    </el-input>
                </el-form-item>

              <el-form-item label=" " v-if="modelForm.type=='PLAN'" prop="storeId" :rules="[{ required: true, message: '请选择商品库', trigger: 'change'}]">
                <div class="el-input el-input-group el-input-group--prepend el-input--medium">
                  <div class="el-input-group__prepend">商品库</div>
                  <!--<el-tooltip placement="top" content="（请选择折扣类型，此项为必选项！）" >
                      <el-button tabIndex="-1">折扣类型</el-button>
                  </el-tooltip>-->
                  <el-select v-model="modelForm.storeId" placeholder="请选择商品库" class="w-100p" @change="getDishes">
                    <el-option
                      v-for="item in storeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
                <el-form-item label=" " prop="startTime" :rules="[ {  required: true, message: '请选择日期', trigger: 'blur' }]">
                  <el-row>
                    <el-col :span="12" style="padding-left: 0;">
                      <div class="el-input el-input-group el-input-group--prepend">
                        <div class="el-input-group__prepend">开始时间</div>
                        <el-date-picker
                          v-model="modelForm.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间"
                          :picker-options="pickerOptions0"
                          @change="getEntryTime2"
                          style="width:100%;"
                        >
                        </el-date-picker>
                      </div>
                    </el-col>
                    <el-col :span="12" style="padding-left: 10px">
                      <div class="el-input el-input-group el-input-group--prepend">
                        <div class="el-input-group__prepend">结束时间</div>
                        <!--<el-tooltip placement="top" content="（请填写结束时间，此项为必填项！）">
                            <el-button tabIndex="-1">结束时间</el-button>
                        </el-tooltip>-->
                        <el-date-picker
                          v-model="modelForm.endTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择结束时间"
                          :picker-options="pickerOptions0"
                          @change="getEntryTime"
                          class="w-100p"
                        >
                        </el-date-picker>
                      </div>
                    </el-col>
                  </el-row>
                </el-form-item>
              <el-form-item label=" " prop="state" :rules="[]" class="text-left" >
                <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium">
                  <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
                    <span>状态</span>
                  </div>
                    <el-radio-group class="radio-group w-100p text-left" v-model="modelForm.state">
                      <el-radio class="radio"  label="NORMAL">正常</el-radio>
                      <el-radio class="radio"  label="DISABLED">禁用</el-radio>
                    </el-radio-group>
                </div>
              </el-form-item>


              <div v-if="modelForm.type=='PLAN' && modelForm.storeId" style="margin-left: 100px;margin-right: 100px;margin-bottom: 15px;">
                <el-row :gutter="20">
                  <el-col :span="10">
                    <el-input placeholder="请输入折扣率" @blur="isNumber(modelForm,'discount')" class="w-100p" v-model="normalDiscount" size="medium">
                      <template slot="prepend">
                        <el-tooltip placement="top" content="（请填写折扣率，如10即10%）">
                          <el-button tabIndex="-1">正常折扣</el-button>
                        </el-tooltip>
                      </template>
                      <template slot="append">%</template>
                    </el-input>
                  </el-col>
                  <el-col :span="10">
                    <el-input placeholder="请输入折扣率" @blur="isNumber(modelForm,'discount')" class="w-100p" v-model="specialDiscount" size="medium">
                      <template slot="prepend">
                        <el-tooltip placement="top" content="（请填写折扣率，如10即10%）">
                          <el-button tabIndex="-1">特价折扣</el-button>
                        </el-tooltip>
                      </template>
                      <template slot="append">%</template>
                    </el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" size="small" @click="batchSet">批量设置折扣</el-button>
                  </el-col>
                </el-row>
              </div>

              <div v-if="modelForm.type!='AllSINGLE'" style="margin-left: 100px;margin-right: 100px">
                <div class="tableTitle">
                  <div class="tableLeft">商品名</div>
                  <div class="tableRight">特价折扣</div>
                  <div class="tableRight">正常折扣</div>
                </div>
                <el-collapse v-model="activeNames" style="margin-left: 0px; margin-right: 0px">
                  <el-collapse-item :name="index" v-for="(item,index) in dishes" :key="index">
                    <template slot="title">
                      <div style="top: 0px;padding-left: 30px;height: 44px;line-height: 44px;text-align: left;padding-bottom:4px;border-bottom: 1px solid #f2f2f2;">
                        <div style="float: left;width: 30%;">
                          <span>{{item.name}}</span>
                        </div>
                        <div style="float: left;width: 60%;line-height: 44px;text-align: right">
                          <el-input placeholder="请输入1-100的值"  style="width: 45%" @click.native.stop @blur="cateIsNumber(item)"  v-model="item.value" @focus="printNum">
                            <template slot="append">%</template>
                          </el-input>
                          <el-input placeholder="请输入1-100的值"  style="width: 45%" @click.native.stop @blur="specialCateIsNumber(item)"  v-model="item.specialValue" @focus="printNum">
                            <template slot="append">%</template>
                          </el-input>
                          <!--&nbsp;&nbsp;&nbsp;<a @click="clealValue(item)">清空</a>-->
                        </div>
                      </div>
                    </template>
                    <div style="height: 44px;line-height: 44px;" v-for="i in item.dishess">
                      <div style="float: left;width: 30%">
                        <span style="color:#000">{{i.name}}</span>
                      </div>
                      <div style="float: left;width: 65%;line-height: 44px;text-align: right;padding-right:10px;">
                        <el-input placeholder="请输入1-100的值"  style="width: 45%"@click.native.stop  @blur="isNumber(i,'value')"  v-model="i.value" @focus="printNum">
                          <template slot="append">%</template>
                        </el-input>
                        <el-input placeholder="请输入1-100的值"  style="width: 45%"@click.native.stop  @blur="isNumber(i,'value')"  v-model="i.specialValue" @focus="printNum">
                          <template slot="append">%</template>
                        </el-input>
                        <!--&nbsp;&nbsp;&nbsp;<a @click="i.value=''">清空</a>-->
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-form>

            <div class="foot-bar-button">
                <el-button type="primary" @click="submitForm('modelForm')" size="medium">提交</el-button>
                <el-button @click="resetForm('modelForm')" size="medium">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template        >
<script>
    //注意路径
    import ElRow from "element-ui/packages/row/src/row";

    export default{
      components: {ElRow},
      props: ['isShow','id'],  //参数
        data(){
            return {
                modelForm: {
                },
                activeNames: ['1'],
                showDialog:false,
                activityId:"",
                isSave:true,
                packageType:[],
                dishes:[],
                pickerOptions0: {
                  disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
                  }
                },
//                pickerOptions1: {
//                },
              detailList:[],
              storeList:[],
              useScenes:[],
              normalDiscount:"",
              specialDiscount:""
            };
        },
        watch:{
            isShow:function(newValue,oldValue){
                this.showDialog=newValue;
                this.modelForm={};
                this.dishes=[];
                console.log(this.id);
                if(newValue){
                    if(this.id!=''){
                        this.activityId=this.id;
                        this.isSave=false;
                        this.$axios.get("pays/discountPlans/"+this.activityId+"/update").then(data=>{
                            this.packageType=data.content.discountTypes;
                          this.storeList=data.content.storeList;

                            data.content.discountPlan.startTime=new Date(data.content.discountPlan.startTime);
                            data.content.discountPlan.endTime=new Date(data.content.discountPlan.endTime);
                            this.modelForm=data.content.discountPlan;
                            if(this.modelForm.type=='PLAN'){
                              this.detailList=data.content.detailList;
                              this.getDishes();
                            }
                            this.useScenes=data.content.useScenes;
                        });
                    }else{
                        this.isSave=true;
                        this.$axios.get("pays/discountPlans/create").then(data=>{
                            this.packageType=data.content.discountTypes;
                            var date = new Date();
                          var d = this.moment(date).format("YYYY-MM-DD");
//                           var s = this.moment(d).add(30, 'days').format('YYYY-MM-DD HH:mm')
                          var s = date.setMonth(date.getMonth()+1);
//                          console.log(",，，，，：",this.moment(s).format("YYYY-MM-DD"));
                          var e = this.moment(s).format("YYYY-MM-DD");

                            data.content.discountPlan.startTime=d+" 00:00:00";
                            data.content.discountPlan.endTime=e+" 23:59:59";
                            this.modelForm=data.content.discountPlan;
                            this.storeList=data.content.storeList;
                            this.useScenes=data.content.useScenes;
//                            this.pickerOptions0.disabledDate=function(time){
////                              console.log(this);
////                                return time.getTime() <= this.modelForm.startTime;
//                            };
//                            this.pickerOptions1.disabledDate=function(time){
////                                return time.getTime() >= this.modelForm.endTime;
//                            }
                        });
                    }
                }
            }
        },
        created(){
            window.this = this;
        },
        methods: {
          batchSet(){
            //设置正常折扣
            if(this.normalDiscount){
              if(this.dishes && this.dishes.length>0){
                for(var i=0;i<this.dishes.length;i++){
                  this.dishes[i].value=this.normalDiscount;
                  if(this.dishes[i].dishess && this.dishes[i].dishess.length>0){
                    for(var n =0;n<this.dishes[i].dishess.length;n++){
                      this.dishes[i].dishess[n].value = this.normalDiscount;
                    }
                  }
                }
              }
            }


            //设置特殊折扣
            if(this.specialDiscount){
              if(this.dishes && this.dishes.length>0){
                for(var i=0;i<this.dishes.length;i++){
                  this.dishes[i].specialValue=this.specialDiscount;
                  if(this.dishes[i].dishess && this.dishes[i].dishess.length>0){
                    for(var n =0;n<this.dishes[i].dishess.length;n++){
                      this.dishes[i].dishess[n].specialValue = this.specialDiscount;
                    }
                  }
                }
              }
            }
            this.$forceUpdate();
            this.specialDiscount=0;
            this.normalDiscount=0;

          },
          getEntryTime(val) {
            console.log(val)
            if(val){
              this.modelForm.endTime = val+" 23:59:59";
            }
//            this.createAt = val;
          },
          getEntryTime2(val) {
            console.log(val)
            if(val){
              this.modelForm.startTime = val+" 00:00:00";
            }
//            this.createAt = val;
          },
          printNum(){
            event.currentTarget.select();
          },
          getDishes(){
            console.log(this.modelForm.storeId);
            if(this.modelForm.storeId && this.modelForm.storeId!='undefined'){
              this.$axios.get("dishes/dishesStores/getDishes?storeId="+this.modelForm.storeId).then(data=>{
                if(data.success){
                  for(let i=0;i<data.content.length;i++){
                    data.content[i].value="";
                    for(let s=0;s<data.content[i].dishess.length;s++){
                      data.content[i].dishess[s].value="";
                      data.content[i].dishess[s].specialValue="";
                    }
                  }
                  this.dishes=data.content;
//                  console.log(this.dishes[0].name);
//                  var dishes = data.content;
//                  console.log(dishes);
                  if(!this.isSave){
                    if(this.dishes && this.dishes.length>0){
                      for(var i=0;i<this.dishes.length;i++){
                        if(this.detailList && this.detailList.length>0){
                          for(var n=0;n<this.detailList.length;n++){
                            if(this.dishes[i].id == this.detailList[n].categoryId){
                              if(!this.detailList[n].dishesId){
//                                console.log(this.dishes[i].name);
//                                console.log(this.dishes[i].id);
//                                console.log(this.detailList[n].categoryId);
//                                console.log(this.detailList[n].rate);
//                                console.log(this.detailList[n].specialRate);
//                                console.log(this.detailList[n]);
                                this.dishes[i].value=this.detailList[n].rate;
                                this.dishes[i].specialValue=this.detailList[n].specialRate;
                              }else{
                                if(this.dishes[i].dishess && this.dishes[i].dishess.length>0){
                                  for(var m=0;m<this.dishes[i].dishess.length;m++){
                                    if(this.dishes[i].dishess[m].id==this.detailList[n].dishesId){
                                      this.dishes[i].dishess[m].value=this.detailList[n].rate;
                                      this.dishes[i].dishess[m].specialValue=this.detailList[n].specialRate;
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }

                 /* if(!this.isSave){
                    var count=0;
                    for(var k=0;k<this.detailList.length;k++){
                      for(let i=0;i<data.content.length;i++){
                        if(this.detailList[k].categoryId==data.content[i].id){
                          console.log(data.content[i]);
                          data.content[i].value=this.detailList[k].rate;
                          data.content[i].specialValue=this.detailList[k].specialRate;
                        }
                        if(data.content[i].dishess && data.content[i].dishess.length>0){
                          for(let s=0;s<data.content[i].dishess.length;s++){
                            if(this.detailList[k].dishesId==data.content[i].dishess[s].id ){
                              console.log("kkkkkk");
                              data.content[i].dishess[s].value=this.detailList[k].rate;
                              data.content[i].dishess[s].specialValue=this.detailList[k].specialRate;
                              count++;
                            }
                            console.log(count);
                            if(count==data.content.length && this.detailList[k].categoryId==data.content[i].id){
                              data.content[i].value=this.detailList[0].rate;
                              data.content[i].specialValue=this.detailList[0].specialRate;
                            }
                          }
                        }



                      }

                    }

                  }*/
                }

              },res=>{})
            }
          },
            goBack() {
                this.router.go(-1);
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var data={};
                        this.modelForm.startTime=this.moment(this.modelForm.startTime).format("YYYY-MM-DD HH:mm:ss")
                      this.modelForm.endTime=this.moment(this.modelForm.endTime).format("YYYY-MM-DD HH:mm:ss")

                      var start = new Date(this.modelForm.startTime);
                      var end = new Date(this.modelForm.endTime);
                      console.log(start.getTime());
                      console.log(end.getTime());
                      if(start.getTime()>end.getTime()){
                        this.$message.error("开始时间不能大于结束时间");
                        return;
                      }


                      data.discountPlans=this.modelForm;
                        if(this.modelForm.type!='AllSINGLE'){
                          var dishesCount=[];
                          for(var i=0;i<this.dishes.length;i++){
                            if(this.dishes[i].value!=""){
                              dishesCount.push(
                                {categoryId:this.dishes[i].id,
                                  dishesId:null,
                                  rate:this.dishes[i].value,
                                  specialRate:this.dishes[i].specialValue
                                }
                                  );
                            }
                            for(var j=0;j<this.dishes[i].dishess.length;j++){
                              if(this.dishes[i].dishess[j].value!=''){
                                dishesCount.push(
                                  {categoryId:this.dishes[i].id,
                                    dishesId:this.dishes[i].dishess[j].id,
                                    rate:this.dishes[i].dishess[j].value,
                                    specialRate:this.dishes[i].dishess[j].specialValue
                                  });
                              }
                            }
                          }
                          console.log(dishesCount);

                          if(dishesCount.length<=0){
                            this.$message.error("请选择商品");
                            return;
                          }
                          data.dishesCount=dishesCount;
                        }
                        if(this.isSave){
                            this.$axios.post("pays/discountPlans/create",data,"json").then(data=>{
                                if(data.status==200){
                                    this.$message({
                                        message:data.message,
                                        type: 'success'
                                    });
                                    this.$emit('addSuccess');
                                }else{
                                    this.$message.error(data.message);
                                }
                            })
                        }else{
                            this.modelForm._method="PUT";
                            this.$axios.put("pays/discountPlans/"+this.activityId+"/update",data,"json").then(data=>{
                                if(data.status==200){
                                    this.$message({
                                        message:data.message,
                                        type: 'success'
                                    });
                                    this.$emit('addSuccess');
                                }else{
                                    this.$message.error(data.message);
                                }
                            });
                        }
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$emit('close');
                this.$refs[formName].resetFields();
                this.showDialog=false;
            },
            handleClose(done){
                this.$emit('close');
                done();
            },
            cateIsNumber(item){
                var r = /^\+?[1-9][0-9]*$/;
                if(!r.test(item.value)){
                    item.value="0.00";
                    for(let i=0;i<item.dishess.length;i++){
                        item.dishess[i].value=0;
                    }
                }else{
                    item.value=item.value
                    for(let i=0;i<item.dishess.length;i++){
                        item.dishess[i].value=item.value;
                    }
                }
            },
          specialCateIsNumber(item){
              console.log(".......");
              console.log(item);
                var r = /^\+?[1-9][0-9]*$/;
                if(!r.test(item.specialValue)){
                    item.specialValue="0.00";
                    for(let i=0;i<item.dishess.length;i++){
                        item.dishess[i].specialValue=0;
                    }
                }else{
                    item.specialValue=item.specialValue
                    for(let i=0;i<item.dishess.length;i++){
                        item.dishess[i].specialValue=item.specialValue;
                    }
                }
            },
            isNumber(item,key){
//              var r=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                var r = /^\+?[1-9][0-9]*$/;
                if( ! r.test(item[key])){
                    item[key]="0.00"
                }else{
                    item[key]=item[key]
                }
            },
            clealValue(item){
                item.value="";
                for(let i=0;i<item.dishess.length;i++){
                    item.dishess[i].value="";
                }
            }
        }
    }
</script>
<style scoped>
    .tableTitle{
        width: 100%;
        height: 44px;
        line-height: 44px;
        /*border: 1px solid #ddd;*/
        font-weight: 700;
      background: #f5f6f7;
      /*margin-left: 100px;*/
    }
    .tableTitle .tableLeft{
        width: 57%;
        float: left;
        height: 100%;
        text-align: left;
        background: #f5f6f7;
        padding-left: 10px;
    }
    .tableTitle .tableRight{
        width: 19%;
        float: right;
        text-align: left;
        height: 100%;
        background: #f5f6f7;
        padding-left: 10px;

    }
    .tableItem{
        width: 100%;
        font-weight: 700;
        height: 40px;
    }
    .tableItem .tableLeft{
        width: 40%;
        float: left;
        text-align: left;
    }
    .tableItem .tableRight{
        width: 60%;
        float: right;
        text-align: center;
    }

    .el-collapse {
      border: 1px solid #ebeef5 !important;
    }
</style>
